package com.gemini.main.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NioSample {

    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();

        // 实例化
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 监听 8080 端口
        serverSocketChannel.socket().bind(new InetSocketAddress(8080));
        serverSocketChannel.configureBlocking(false);

        //向Selector注册通道
        serverSocketChannel.register(selector, SelectionKey.OP_READ);

        for (; ; ) {
            if (selector.select() == 0) continue;

            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> selectionKeyIterator = selectionKeys.iterator();
            while (selectionKeyIterator.hasNext()) {
                SelectionKey key = selectionKeyIterator.next();
                if (key.isAcceptable()) {
                    //TODO a connection was accepted by a ServerSocketChannel.
                } else if (key.isConnectable()) {
                    //TODO a connection was established with a remote server.
                } else if (key.isReadable()) {
                    //TODO a channel is ready for reading

                } else if (key.isWritable()) {
                    //TODO a channel is ready for writing
                }

                selectionKeyIterator.remove();

            }
        }
    }
}
